#encoding:utf-8

'''
@version    : 0.1
@author     : guozhao
@time       : 2018/5/12 上午11:17
'''

import re
import datetime
import json
from elasticsearch import Elasticsearch


log_path = "alert_crm.log"
#log_path = "/u01/app/oracle/diag/rdbms/crm/crm/trace/alert_crm.log"

def getlog():

    patter = re.compile(r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun)")

    fd = open(log_path, "r")
    offset = getLogOffset()
    fd.seek(offset, 0)

    cn = 0

    content = ""
    for line in fd:

        ts = ""
        if re.search(r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun)", line):
            ts = line.strip()
            try:
                ts_f = str(datetime.datetime.strptime(ts, '%a %b %d %H:%M:%S %Y'))
            except Exception as e:
                cn = cn + 1
                continue


            log_str = ts_f + " " + content

            yield {"ts": ts_f, "content":content}

            content = ""
            log_str = ""


        else:
            content = content + line.strip()

    setLogOffset(fd.tell())
    fd.close()




# 记录文件位置
def setLogOffset(log_offset):
    with open("log-offset", "w+") as fd:
        fd.write(str(log_offset))


def getLogOffset():
    with open("log-offset", "r") as fd:
        offset = fd.readline().strip()

        if len(offset) == 0:
            return 0
        else:
            return int(offset)



def main():
    for item in getlog():
        print item
        dic_json = json.dumps( item )
        try:
            es.index( index='langjiu-logs', doc_type='logs', body=dic_json )
        except Exception as e:
            print 'send button_opr log to es error', e




if __name__ == "__main__":
    es = Elasticsearch('172.192.100.12')
    main()
